package com.data.common.util;


import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.data.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * IOT token 验证
 */
@Slf4j
@SuppressWarnings("ALL")
public class JwtIOTAuthUtil {
    // Token过期时间30分钟（用户登录过期时间是此时间的两倍，以token在reids缓存时间为准）
    public static final long EXPIRE_TIME = 30 * 60 * 1000;

    private static final String IOT_SECRET = "Gwxm722fPdvMB1Bo";


    public static String getTokenByRequest(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader(CommonConstant.IOT_TOKEN);
        }
        //截取长度

        return checkHead(token);
    }

    public static String getUserNameByRequest(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader(CommonConstant.IOT_TOKEN);
        }
        //截取长度

        return checkUserNameHead(token);
    }

    public static boolean verify(String token,String username) {
        try {
            if(StrUtil.isEmpty(token)){
                return false;
            }
            if(token.startsWith(CommonConstant.IOT_TOKEN_START)){
                token = token.substring(CommonConstant.IOT_TOKEN_START.length());
            }
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(IOT_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (TokenExpiredException e){
            log.error(e.getMessage(),e);
            return false;
        } catch (Exception exception) {
            throw exception;
        }
    }

    /**验证token是否有效
     * @param auth
     * @return
     */
    public static String checkHead(String auth) {

        String userId = "";
        try {
            auth = auth.substring("Bearer ".length());

            Algorithm algorithm = Algorithm.HMAC256("Gwxm722fPdvMB1Bo");
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 验证签名 能正常解析说明验签成功
            DecodedJWT jwt = verifier.verify(auth);
            Date time = jwt.getExpiresAt();

            DecodedJWT jwt2 = JWT.decode(auth);
            String username = jwt2.getClaim("username").asString();
           // userId = jwt2.getClaim("userId").asString();
           // userId = jwt2.getClaim("userId").asInt().toString();
            userId = jwt2.getClaim("userId").asInt().toString();

        } catch (IllegalArgumentException e) {
            log.error("验证authToken失败 {}", e);
        } catch (JWTVerificationException e) {
            log.error("验证authToken失败 {}", e);
        }
        return String.valueOf(userId);
    }

    /**验证token是否有效
     * @param auth
     * @return
     */
    public static String checkUserNameHead(String auth) {

        String username = "";
        try {
            auth = auth.substring("Bearer ".length());

            Algorithm algorithm = Algorithm.HMAC256("Gwxm722fPdvMB1Bo");
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 验证签名 能正常解析说明验签成功
            DecodedJWT jwt = verifier.verify(auth);
            Date time = jwt.getExpiresAt();

            DecodedJWT jwt2 = JWT.decode(auth);
            username = jwt2.getClaim("username").asString();
            // userId = jwt2.getClaim("userId").asString();
            // userId = jwt2.getClaim("userId").asInt().toString();

        } catch (IllegalArgumentException e) {
            log.error("验证authToken失败 {}", e);
        } catch (JWTVerificationException e) {
            log.error("验证authToken失败 {}", e);
        }
        return String.valueOf(username);
    }

    public static String sign(String username) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(IOT_SECRET);
        // 附带username信息
        return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
    }

    public static String sign(String username,String userId) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(IOT_SECRET);
        // 附带username信息
        return JWT.create().withClaim("username", username)
                .withClaim("userId",userId)
                .withExpiresAt(date).sign(algorithm);
    }
}
